import ChessRelated from './chessRelated'
import { ChessList } from './intenface'

const _chessList: ChessList = {}
const piece: any[] = [{ b: 5 }, { p: 2 }, { c: 2 }, { m: 2 }, { x: 2 }, { s: 2 }, { j: 1 }]
const camps = ['red', 'black']
const initChessPosition: any = {
  b: [{ x: 6, y: 0 }, { x: 6, y: 2 }, { x: 6, y: 4 }, { x: 6, y: 6 }, { x: 6, y: 8 }],
  p: [{ x: 7, y: 1 }, { x: 7, y: 7 }],
  c: [{ x: 9, y: 0 }, { x: 9, y: 8 }],
  m: [{ x: 9, y: 1 }, { x: 9, y: 7 }],
  x: [{ x: 9, y: 2 }, { x: 9, y: 6 }],
  s: [{ x: 9, y: 3 }, { x: 9, y: 5 }],
  j: [{ x: 9, y: 4 }],
  B: [{ x: 3, y: 0 }, { x: 3, y: 2 }, { x: 3, y: 4 }, { x: 3, y: 6 }, { x: 3, y: 8 }],
  P: [{ x: 2, y: 1 }, { x: 2, y: 7 }],
  C: [{ x: 0, y: 0 }, { x: 0, y: 8 }],
  M: [{ x: 0, y: 1 }, { x: 0, y: 7 }],
  X: [{ x: 0, y: 2 }, { x: 0, y: 6 }],
  S: [{ x: 0, y: 3 }, { x: 0, y: 5 }],
  J: [{ x: 0, y: 4 }]
}

let _chessRelated: ChessRelated
// 建立10*9的矩阵，存储棋盘棋子的位置
const _chessBoard: string[][] = new Array(10)
for (let i = 0; i < _chessBoard.length; i++) {
  _chessBoard[i] = new Array(9).fill('')
}

// 初始化_chessList 
camps.forEach((camp, index) => {
  piece.forEach(p => {
    const key = Object.keys(p)[0]
    let campKey = key
    let isRed = true
    if (index & 1) {
      campKey = key.toUpperCase()
      isRed = false
    }
    for (let i = 0; i < p[key]; i++) {
      const x = 0
      const y = 0
      const id = `${campKey}${i + 1}`
      _chessList[id] = {
        src: require(`../../assets/${camp}/${campKey}.png`),
        display: 'none',
        isRed,
        x,
        y
      }
    }
  })
})

const boxTyep = ['r_box', 'b_box']
const _boxList: ChessList = {}

boxTyep.forEach((type) => {
  for (let i = 1; i <= 2; i++) {
    _boxList[`${type}${i}`] = {
      src: require(`../../assets/${type}.png`),
      x: 0,
      y: 0,
      display: 'none'
    }
  }
})

_chessRelated = new ChessRelated(_chessBoard)

export { _chessList, _boxList, _chessRelated, _chessBoard }

export function initChessBoard(chessCharacter: number, _chessList: ChessList, _chessBoard: string[][]) {
  // 初始化 _chessBoard 和 _chessList 
  camps.forEach((camp, index) => {
    piece.forEach(p => {
      const key = Object.keys(p)[0]
      let campKey = key
      if (index & 1) {
        campKey = key.toUpperCase()
      }
      for (let i = 0; i < p[key]; i++) {
        let x: number
        let y: number
        if (chessCharacter == 2) {
          x = 9 - initChessPosition[campKey][i].x
          y = 8 - initChessPosition[campKey][i].y
        } else {
          x = initChessPosition[campKey][i].x
          y = initChessPosition[campKey][i].y
        }
        const id = `${campKey}${i + 1}`
        _chessBoard[x][y] = id
        _chessList[id].display = 'block'
        _chessList[id].history = []
        _chessList[id].x = x
        _chessList[id].y = y
      }
    })
  })
}